package com.yupi.springbootinit.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.entity.Picture;
import com.yupi.springbootinit.service.PictureService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 图片服务
 *
 * @author LZH
 * @date 2023/5/7
 */
@Slf4j
@Service
public class PictureServiceImpl implements PictureService {

    private static Pattern URL_PATTERN = Pattern.compile("m=\"\\{(.*)}\"?");
    private static Pattern TITLE_PATTERN = Pattern.compile("<li><a title=\"(.*)\"(.*)href?");

    @Override
    public Page<Picture> searchPicture(String searchText, long pageNum, long pageSize) {
        long current = (pageNum - 1) * pageSize;
        String url = "https://cn.bing.com/images/search?q=" + searchText + "&first=" + current + "&cw=1269&ch=583";
        Document document = null;
        try {
            document = Jsoup.connect(url)
                    .ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据获取异常");
        }

        //禁用转义
        String documentNew = Parser.unescapeEntities(document.toString(), false);
        Matcher matcher = URL_PATTERN.matcher(documentNew);

        List<String> jsonList = new ArrayList<>();
        while (matcher.find()) {
            String str = matcher.group(0);
            str = str.substring(3);
            str = str.substring(0, str.length() - 1);
            jsonList.add(str);
        }

        Page<Picture> picturePage = new Page<>(pageNum, pageSize);
        List<String> urlList = null;
        try {
            urlList = jsonList.stream()
                    .map(json -> {
                        Map<String, Object> map = JSONUtil.toBean(json, Map.class);
                        String turl = (String) map.get("turl");
                        return turl;
                    }).collect(Collectors.toList());

            matcher = TITLE_PATTERN.matcher(documentNew);

        } catch (Exception e) {
            log.error("Map类型转换异常", e);
            return picturePage;
        }
        List<String> titleList = new ArrayList<>();
        while (matcher.find()) {
            String group = matcher.group(0);
            group = group.replace("<li><a title=\"", "").replace("\" href", "");
            titleList.add(group);
        }
        List<Picture> pictures = new ArrayList<>();
        for (int i = 0; i < urlList.size(); i++) {
            Picture picture = new Picture();
            picture.setTitle(titleList.get(i));
            picture.setUrl(urlList.get(i));
            pictures.add(picture);
            if (pictures.size() >= pageSize) {
                break;
            }
        }

        picturePage.setRecords(pictures);
        return picturePage;
    }
}
